package com.student;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Arrays;

public class TCPServer {
	
	private static final int PORT = 1000;
	
	public static void main(String[] args) {
		ServerSocket socket = null;
		try {
			//创建服务器并绑定IP和端口
			//写法一
			socket = new ServerSocket();
			SocketAddress address = new InetSocketAddress(PORT);//端口
			address = new InetSocketAddress(InetAddress.getByName("192.168.31.125"),PORT);
			socket.bind(address);
			
			//写法二
//			socket = new ServerSocket(PORT);//绑定服务所有IP的端口
//			socket = new ServerSocket(PORT, 50);
			
			//port：端口
			//backlog：待办的事务，请求传入链接队列的最大长度，默认50
			//InetAddress：IP地址
			
			System.out.println("服务器创建完成");
			System.out.println(socket.getLocalPort());
			System.out.println(socket.getInetAddress());//
			
			//接收一个客户端链接,阻塞的方法，必须要有客户端链接才会执行完成
			Socket client = socket.accept();
			
			System.out.println(client.getPort());
			System.out.println(client.getInetAddress());
			System.out.println(client.getLocalPort());
			System.out.println(client.getLocalAddress());
			System.out.println(client.getRemoteSocketAddress());
			System.out.println(client.getInputStream());
			System.out.println(client.getOutputStream());
			
			//接收一段客户端发送的字节数组
			InputStream in = client.getInputStream();
			in.read();
			byte[] bs = new byte[10];
			int len = in.read(bs);
			System.out.println("接收一段客户端的字节数组：" + len + "=" + Arrays.toString(bs));
			
			//向客户端发送一段字节数组
			OutputStream out = client.getOutputStream();
			bs[9] = 9;
			out.write(bs);
			
			System.out.format("关闭客户端[%s:%s]",client.getInetAddress().getHostAddress(),client.getPort());
			client.close();//关闭客户端
			socket.close();//关闭服务器端
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
